//
//  AllButtonController.m
//  IntimateGift
//
//  Created by 蔡宏业 on 14/12/22.
//  Copyright (c) 2014年 蔡宏业. All rights reserved.
//

#import "AllButtonController.h"
#import "AllButtonWebViewController.h"
#import "SpecialDetailViewController.h"
#import "SpeciallCollectionViewCell.h"
#import "Special.h"
#import "UIImageView+WebCache.h"
#import "NetHandler.h"
#import "WebViewDetail.h"
#import "AllGroup.h"
#import "DetailsViewController.h"
#import "UIScrollView+Extension.h"
#import "UIScrollView+MJRefresh.h"

@interface AllButtonController ()<UICollectionViewDataSource,UIBarPositioningDelegate,UICollectionViewDelegateFlowLayout>
@property (nonatomic,retain)UICollectionView *collectionView;
@property (nonatomic, assign)NSInteger num;
@end

@implementation AllButtonController


- (void)dealloc
{
    [_arr release];
    [_special release];
    [_collectionView release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.arr = [NSMutableArray array];
        self.num = 12;
        
    }
    return self;
}


-(void)handledate
{
    NSString *str = [NSString stringWithFormat:@"http://api.liwushuo.com/v1/collections/%@/posts?limit=12&offset=0",self.special.ScrollViewid];
   [ NetHandler getDataWithUrl:str completion:^(NSData *data) {
        NSError *error = nil;
        id  result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        
       NSDictionary *dic = [NSDictionary dictionary];
        dic = [result objectForKey:@"data"];
        NSArray *arr = [NSArray array];
        arr = [dic objectForKey:@"posts"];
        //        Special *hehe = [[Special alloc]init];
        for (NSDictionary *dictemp in arr) {
            //利用字典将对象初始化
          AllGroup *hehe =[[AllGroup alloc] initWithDictionary:dictemp];
//            NSLog(@"-------%@", hehe.title);
            [self.arr addObject:hehe];
            [hehe release];
        }
        [self installCollection];
        [self setupRefresh];
    }];
   


}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.navigationController.navigationBar.alpha = 1;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;
}




- (void)installCollection
{
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.translucent = NO;
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    //flowLayout.itemSize = CGSizeMake(170, 120);
    
    [flowLayout setScrollDirection:(UICollectionViewScrollDirectionVertical)];
    
   // self.view.backgroundColor = [UIColor redColor];
    //最小行间距
    flowLayout.minimumLineSpacing = 30;
    
    flowLayout.headerReferenceSize = CGSizeMake(self.view.bounds.size.width/2 , 0);
    
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height + 50) collectionViewLayout:flowLayout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.view addSubview:self.collectionView];
    [_collectionView release];
    
    
    //注册一个cell类
    [self.collectionView registerClass:[SpeciallCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerReuse"];
   
    
}

- (void)viewDidLoad {
    self.navigationItem.title = self.special.title;
    self.navigationController.navigationBar.translucent = NO;
    [super viewDidLoad];
    [self handledate];
    
    
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerReuse" forIndexPath:indexPath];
    
    view.backgroundColor = [UIColor blackColor];
    
    return view;
    
}




//每个分区上的元素个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arr.count;
    
}
//设置元素内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    SpeciallCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor whiteColor];
    AllGroup *group = [self.arr objectAtIndex:indexPath.row];
    NSString *str = [group.cover_image_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    [cell.myImageView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"zhanwei.jpg"]];
    cell.titleLabel.text = group.title;
    return cell;
}

//设置元素的大小框
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    UIEdgeInsets top = {5,10,15,5};
    return top;
    
}
//设置顶部的大小
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
//{
//    CGSize size = {0,0};
//    return size;
//}
//设置每个元素的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(self.view.bounds.size.width/3.4, 100);
    
}
//点击元素出发事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    AllGroup *group = [self.arr objectAtIndex:indexPath.item];
    
    DetailsViewController *detail = [[DetailsViewController alloc]init];
    detail.group = group;
    detail.mark = 2;
    [self.navigationController pushViewController:detail animated:YES];
//    [detail release];
  
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)setupRefresh
{
    //    NSLog(@"进入了setupRefresh");
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    
    [self.collectionView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //进入刷新状态(一进入程序就下拉刷新)
    [self.collectionView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.collectionView addFooterWithTarget:self action:@selector(footerRereshing)];
}


- (void)headerRereshing
{
    NSString *str =[[NSString  alloc] initWithFormat:@"http://api.liwushuo.com/v1/collections/%@/posts?limit=12&offset=0",self.special.ScrollViewid];
    [ NetHandler getDataWithUrl:str completion:^(NSData *data) {
        NSError *error = nil;
        id  result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        
        NSDictionary *dic = [NSDictionary dictionary];
        dic = [result objectForKey:@"data"];
        NSArray *arr = [NSArray array];
        arr = [dic objectForKey:@"posts"];
        [self.arr removeAllObjects];
        for (NSDictionary *dictemp in arr) {
            //利用字典将对象初始化
            AllGroup *hehe =[[AllGroup alloc] initWithDictionary:dictemp];
            [self.arr addObject:hehe];
            [hehe release];
        }
        
    }];
    
    
    
    //2. 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.collectionView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.collectionView headerEndRefreshing];
    });
}

//   进入加载状态
- (void)footerRereshing
{
    NSString *str =[[NSString  alloc] initWithFormat:@"http://api.liwushuo.com/v1/collections/%@/posts?limit=12&offset=%ld",self.special.ScrollViewid, self.num];
    [ NetHandler getDataWithUrl:str completion:^(NSData *data) {
        NSError *error = nil;
        id  result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
        
        NSDictionary *dic = [NSDictionary dictionary];
        dic = [result objectForKey:@"data"];
        NSArray *arr = [NSArray array];
        arr = [dic objectForKey:@"posts"];
        //        Special *hehe = [[Special alloc]init];
        for (NSDictionary *dictemp in arr) {
            //利用字典将对象初始化
            AllGroup *hehe =[[AllGroup alloc] initWithDictionary:dictemp];
            //            NSLog(@"-------%@", hehe.title);
            [self.arr addObject:hehe];
            
        }
        self.num = self.num + 12;
    }];
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        
            [self.collectionView  reloadData];
            [self.collectionView footerEndRefreshing];
        
        
    });
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
